package com.example.springboot.service.Impl;

import com.example.springboot.entity.CollectIncorrectQuestion;
import com.example.springboot.entity.vo.IncorrectQuestionVo;
import com.example.springboot.mapper.CollectIncorrectQuestionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class CollectIncorrectQuestionService {

    @Autowired
    private CollectIncorrectQuestionMapper collectIncorrectQuestionMapper;

    public Integer addCollect(Integer userId, Integer incorrectQuestionId) {
        CollectIncorrectQuestion collect = new CollectIncorrectQuestion();
        collect.setUserId(userId);
        collect.setIncorrectQuestionId(incorrectQuestionId);
        collect.setCreatedAt(Timestamp.valueOf(LocalDateTime.now()));
        Integer res =collectIncorrectQuestionMapper.insertCollectIncorrectQuestion(collect);
        return collect.getId();
    }

    public CollectIncorrectQuestion getCollectById(Integer id) {
        return collectIncorrectQuestionMapper.getCollectById(id);
    }

    public void removeCollect(Integer id) {
        collectIncorrectQuestionMapper.deleteCollect(id);
    }

    public List<IncorrectQuestionVo> getCollectsByUserId(Integer userId,Integer pageNum,Integer pageSize) {
        pageNum = (pageNum - 1) * pageSize;
        List<IncorrectQuestionVo> incorrectQuestions = collectIncorrectQuestionMapper.getCollectsByUserId(userId, pageNum, pageSize);
        if (incorrectQuestions == null || incorrectQuestions.isEmpty()) {
            return incorrectQuestions;
        }
        System.out.println(incorrectQuestions);
        incorrectQuestions.stream().forEach(item->{
            item.setIsCollectUser(collectIncorrectQuestionMapper.isIncorrectQuestionCollected(userId, item.getId()));
        });
        System.out.println(incorrectQuestions);
        incorrectQuestions.stream()
                .filter(IncorrectQuestionVo::getIsCollectUser) // 只处理 isCollectUser 为 true 的项
                .forEach(item -> {
                    Integer collectId = collectIncorrectQuestionMapper.getCollectIdByUserIdAndIncorrectQuestionId(userId, item.getId());
                    item.setCollectId(collectId); // 假设 IncorrectQuestionVo 中有 collectId 字段
                });
        System.out.println(incorrectQuestions);
        return incorrectQuestions;
    }
}